import CryptoJS from 'crypto-js'

export function aesCBCEncrypt(text: string, secretKey: string) {
    const keyHex = CryptoJS.enc.Utf8.parse(secretKey)
    const ivHex = keyHex.clone()
    // 前16字节作为向量
    ivHex.sigBytes = 16
    ivHex.words.splice(4)
    const messageHex = CryptoJS.enc.Utf8.parse(text)
    const encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, {
        iv: ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
}

export function transformRecordToOption<T extends Record<string, string>>(record: T, isKeyNumber?: boolean) {
    return Object.entries(record).map(([value, label]) => ({
        value: isKeyNumber ? Number(value) : value,
        label
    })) as Common.Option<keyof T>[]
}

export function transformOptionToRecord(options: Common.Option<number>[]) {
    const obj: Record<number, string> = {}
    options.forEach(item => {
        obj[item.value] = item.label
    })
    return obj
}

export function fileToBase64(file: File): Promise<string> {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    return new Promise(resolve => {
        reader.onload = ev => {
            resolve(ev.target!.result as string)
        }
    })
}
